﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cbs.Lucky.Model;
using Cbs.Lucky.ViewModels;
using Dapper;
using Dapper.Contrib.Extensions;
using NLog;

namespace Cbs.Lucky.Services.Impl
{
    public class DataItemService : IDataItemService
    {
        private static Logger Logger = LogManager.GetCurrentClassLogger();
        public DataItemService(
            IDbConnection db)
        {
            Db = db;
        }

        public IDbConnection Db { get; }

        public async Task<List<DataItem>> Query(DataItemQueryParameter parameter)
        {
            var list = (await Db
                .QueryAsync<DataItem>($@"
SELECT * FROM DataItem ORDER BY Id DESC
LIMIT {parameter.LimitNum}"))
                .ToList();
            return list;
        }

        public async Task<bool> Save(DataItem data)
        {
            try
            {
                var exisitData = await Db.QueryFirstOrDefaultAsync<DataItem>(@"
SELECT *
FROM DataItem
WHERE Id = @Id
LIMIT 1", data);
                if (exisitData == null)
                {
                    await Db.InsertAsync(data);
                }
                else
                {
                    data.CreateTime = DateTime.Now;
                    await Db.UpdateAsync(data);
                }
            }
            catch (Exception ex)
            {
                Logger.Error($"DataItemService Save Message:{ex.Message},StackTrace:{ex.StackTrace}");
                return false;
            }
            return true;
        }
    }
}
